import { Next } from "koa";
import { body, middlewares, routeConfig, z } from "koa-swagger-decorator";
import { Context } from "koa"; // 注意：这里应导入 koa 的 Context，而非 vm 的
import uploadService from "@/service/upload.service";
import authMiddleware from "@/middleware/auth.middleware";
import { File } from "formidable";
export class UploadController {
  /**
   * 单文件上传
   */
  @routeConfig({
    method: "post",
    path: "/file/upload/single",
    summary: "单文件上传",
    tags: ["文件"],
    description: "支持上传图片（jpg、png、gif），最大 10MB",
  })
  @middlewares([authMiddleware.verifyAuth])
  async uploadSingle(ctx: Context, next: Next) {
    try {
      if (!ctx.request.files || Array.isArray(ctx.request.files)) {
        throw new Error("文件上传格式错误");
      }

      // 获取上传的文件（koa-body 会将文件挂载到 ctx.request.files）
      const file = ctx.request.files?.file;
      if (!file) {
        throw new Error("未上传文件");
      }

      const uploadFile = Array.isArray(file)
        ? (file[0] as unknown as File)
        : (file as File);
      // 调用服务层处理文件
      const result = await uploadService.handleSingleFile(uploadFile);

      ctx.body = {
        success: true,
        data: result,
        errorMessage: null,
      };
      ctx.status = 200;
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "文件上传失败",
      };
      ctx.status = error.status || 400;
    }
  }

  /**
   * 批量删除文件
   */
  @routeConfig({
    method: "delete",
    path: "/file/delete",
    summary: "批量删除文件",
    tags: ["文件"],
  })
  @body(
    z.object({
      filenames: z.array(z.string()).describe("要删除的文件名列表"),
    })
  )
  @middlewares([authMiddleware.verifyAuth])
  async deleteFiles(ctx: Context, next: Next) {
    try {
      const { filenames } = ctx.request.body as { filenames: string[] };
      if (!filenames || filenames.length === 0) {
        throw new Error("请提供要删除的文件名列表");
      }

      const result = await uploadService.deleteFiles(filenames);

      ctx.body = {
        success: true,
        data: result,
        errorMessage: null,
      };
      ctx.status = 200;
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "文件删除失败",
      };
      ctx.status = error.status || 400;
    }
  }
}
